package com.demo.common.core.config;

import com.demo.common.core.converter.LocalDateConverter;
import com.demo.common.core.converter.LocalDateTimeConverter;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.converter.Converter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 时间格式转化
 *
 * @author DayDayUp
 * @datetime 2023-08-31 9:21
 **/
public class LocalDateTimeConfig {

    private final static String dateTimeFormat = "yyyy-MM-dd HH:mm:ss";
    private final static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private final static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateTimeFormat);

    /**
     * 入参 String -> LocalDate
     * 千万不能把对应的converter合并过来变成lambda写法，否则不生效
     */
    @Bean
    public Converter<String, LocalDate> localDateConverter() {
        return new LocalDateConverter(dateFormatter);
    }

    /**
     * 入参 String -> LocalDateTime
     * 千万不能把对应的converter合并过来变成lambda写法，否则不生效
     */
    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter() {
        return new LocalDateTimeConverter(dateTimeFormatter);
    }

    /**
     * 出参 LocalDateTime -> String
     * 出参 LocalDate -> String
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        return builder -> {
            builder.simpleDateFormat(dateTimeFormat);
            builder.serializerByType(LocalDateTime.class,new LocalDateTimeSerializer(dateTimeFormatter));
            builder.serializerByType(LocalDate.class,new LocalDateSerializer(dateFormatter));

            builder.deserializerByType(LocalDateTime.class,new LocalDateTimeDeserializer(dateTimeFormatter));
            builder.deserializerByType(LocalDate.class,new LocalDateDeserializer(dateFormatter));
        };
    }
}
